<!--订单列表右侧抽屉-->
<template>
    <div class="drawer-box">
        <a-drawer :title="drawerTitle" wrapClassName="drawer-box" placement="right" :closable="true"
            :visible="drawerVisible" :after-visible-change="afterVisibleChange" @close="onClose" width="900">
            <!-- <a-col style="color:red;font-size:12px">只有审核通过的单据才能进行选单操作</a-col> -->
            <a-row :gutter="[0, 16]">
                <a-col :span="24">
                    <a-input-search class="search-btn" v-model="searchText" :placeholder="searchPlaceholder"
                        ref="searchInput" @search="searchList" enter-button></a-input-search>
                </a-col>
            </a-row>
            <a-row :gutter="[0, 16]">
                <a-col :span="24">
                    <!-- <a-table class="search-table-list" :columns="searchCloums" :row-selection="{ columnWidth:30,selectedRowKeys: selectedRowKeysMain, onChange: onSelectChangeMain,type:'radio' }" :scroll="{x:500,y:500}" :data-source="searchBackData" :customRow="customClick" :rowClassName="rowClassName" bordered :pagination="pagination"> -->
                    <a-table rowKey="id" :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }" class="search-table-list" :columns="searchCloums" :scroll="{ x: 500, y: 500 }"
                        :data-source="searchBackData" :rowClassName="rowClassName" bordered
                        :pagination="pagination">
                        <slot slot="businessType" slot-scope="text,record">
                            {{ handleBusinessType(record) }}
                        </slot>
                        <slot slot="sourceVoucherType" slot-scope="text">
                            {{ conversionOrderName(text) }}
                        </slot>
                    </a-table>
                </a-col>
                <a-col :span="24" v-show="searchDetailsHover">
                    <!-- <a-table class="search-table-list" :columns="searchCloumsDetails" :row-selection="{ columnWidth:30,selectedRowKeys: selectedRowKeysDetails, onChange: onSelectChangeDetails }" :scroll="{x:500,y:500}" :data-source="searchBackDataDetails" bordered :pagination="false"> -->
                    <a-table rowKey="id" :row-selection="{ selectedRowKeys: selectedRowKeysDetail, onChange: onSelectChangeDetail }" class="search-table-list" :columns="searchCloumsDetails" :scroll="{ x: 500, y: 500 }"
                        :data-source="searchBackDataDetails" bordered :pagination="false">
                        <slot slot="sourceVoucherType" slot-scope="text">
                            {{ conversionOrderName(text) }}
                        </slot>
                    </a-table>
                </a-col>
            </a-row>
            <div
        :style="{
          position: 'absolute',
          bottom: 0,
          width: '100%',
          borderTop: '1px solid #e8e8e8',
          padding: '10px 16px',
          textAlign: 'right',
          left: 0,
          background: '#fff',
          borderRadius: '0 0 4px 4px',
        }"
      >
        <a-button type="primary" @click="onSubmit">
          确定
        </a-button>
      </div>
        </a-drawer>
    </div>
</template>
<script>

import { list as listDesign } from "@/api/erp/voucherDesign"; //动态表单数据
import { list as listSearch } from '@/api/purchase/voucherDesign';//搜索列表
import { deepCopy } from "@/utils/tool/object";

import { IdFieldToNameField } from "@/utils/customize";
import { conversionOrderName } from "@/utils/tool/parametric-switch";
import { deleteMainCommonFild } from "@/utils/voucherUtils";

export default {
    props: {
        unitData: {//单计量
            type: Object,
            default: () => { }
        },
        unitsDataDetails: {//多计量的子计量
            type: Object,
            default: () => { }
        },
        businessType: {
            type: Number
        },
        parentSourceCode: {
            type: String
        },
        productionPlanToSalesOrder: {
            type: Boolean,
            default: false,
        }
    },
    data() {
        return {
            selectedRowKeys: [],
            selectedRowKeysDetail: [],
            sourceCode: '',//必写，获取动态表单的参数
            drawerVisible: false,
            drawerTitle: '搜索列表',
            dynamicFormData: [],    //动态表单数据
            searchArray: [],        //搜索条件
            searchPlaceholder: '',  //搜索框提示可搜索字段
            searchText: '',         //搜索输入框
            searchCloums: [],
            searchCloumsDetails: [],  //明细cloums
            searchBackData: [],
            searchDetailsHover: [],  //鼠标移入当前数据的详细信息数据
            searchBackDataDetails: [],             //选中的详情
            ischoose: false,        //是否是选单（选单需要删除id）
            voucherState: null,      //单据审核状态  
            selectedRowMainKeys: null,
            selectedRowMainData: null,
            selectedRowDetailsKeys: null,
            selectedRowDetailsData: null,
            pagination: {
                size: "small",
                defaultPageSize: 10,
                current: 1,
                pageSize: 10,
                total: 0,
                showTotal: total => {
                    return (
                        <div>
                            共 {total} 条数据，每页
                            <a-input style="height:22px !important;width:3.2rem;"
                                value={this.pagination.pageSize}
                                min={1}
                                max={10}
                                size="small"
                                step={1}
                                onPressEnter={e => this.changePageSize(e)}
                            />
                            条
                        </div>
                    );
                },
                onChange: (page, pageSize) => {
                    this.pagination.current = page;
                    this.pagination.pageSize = pageSize;

                    this.boxPostData.page = {
                        current: this.pagination.current,
                        size: this.pagination.pageSize,
                    };

                    Object.assign(this.postData, this.boxPostData);
                    this.searchList();
                },
                showQuickJumper: true,
                showLessItems: true,
                choiceBusinessType: null,//选单传入的业务类型
            },
            mouseIndex: null,
            customClick: (record, index) => ({
                on: {
                    mouseenter: (event) => {
                        if (this.$route.path !== '/production/productionPlan') {
                            event.preventDefault();
                            this.mouseIndex = index;
                            this.searchDetailsHover = record;
                            const detaileList = [];
                            record.detailList.forEach(item => {
                                const item1 = { ...item };
                                detaileList.push(item1);
                            })
                            this.showDetailes(detaileList);
                        }
                    },
                    click: (event) => {
                        event.preventDefault();
                        //深拷贝
                        record = deepCopy(record, true);


                        // record.updateDate = null;
                        // record.createUserId = null;
                        // record.createDate = null;
                        // record.reviewerDate = null;

                        //关闭侧边栏赋值给父组建
                        this.drawerVisible = false;

                        //选单
                        this.$set(record, 'sourceVoucherId', record.id);    //来源id
                        this.$set(record, 'sourceVoucherCode', record.voucherCode);    //来源单号
                        this.$set(record, 'sourceVoucherDate', record.voucherDate);    //来源日期
                        this.$set(record, 'sourceVoucherType', this.sourceCode);   //来源单据

                        if (this.$route.path == '/production/productionPlan') {
                            //生产订单选销售订单 传值
                            this.$set(record, 'saleOrderId', record.id);
                            this.$set(record, 'saleOrderCode', record.voucherCode);
                        }

                        //选单明细 来源置入
                        for (let i = 0; i < record.detailList.length; i++) {

                            if (this.$route.path == '/production/productionPlan') {
                                //生产订单选销售订单 传值
                                this.$set(record.detailList[i], 'saleOrderDetailId', record.detailList[i].id);    //id
                                this.$set(record.detailList[i], 'needDate', record.detailList[i].deliveryDate);
                                this.$set(record.detailList[i], 'planEndDate', record.detailList[i].deliveryDate);
                                this.$set(record.detailList[i], 'crmName', record.crmName);
                            }

                            // record.detailList[i].sourceVoucherId = record.detailList[i].id;
                            let item = record.detailList[i];
                            item.sourceVoucherId = record.id;
                            item.sourceVoucherCode = record.voucherCode;    //来源单号
                            item.sourceVoucherDate = record.voucherDate;    //来源日期
                            item.sourceVoucherType = record.sourceVoucherType;    //来源单据



                            let { businessType } = this.postData;
                            console.log("选单查询条件：businessType：", businessType);
                            if (businessType == 1) {
                                item.baseQuantity = Math.abs(item.baseQuantity) - (item.cumRetQuantity ? item.cumRetQuantity : 0);
                            } else if (this.$route.path == '/production/productionPlan') {
                                //生产订单不需要处理数量
                            } else if (businessType == 2) {
                                item.baseQuantity = Math.abs(item.baseQuantity) - (item.cumExecuteQuantity ? item.cumExecuteQuantity : 0);
                            } else if (businessType == 4) {
                                item.baseQuantity = Math.abs(item.baseQuantity) - (item.cumInvoiceQuantity ? item.cumInvoiceQuantity : 0);
                                console.log("businessType == 4: item.baseQuantity:", item.baseQuantity);
                            }
                            // 未质检 数量查询
                            else if (businessType == 6) {

                                item.baseQuantity = Math.abs(item.baseQuantity) - (item.cumQualityCheckQuantity ? item.cumQualityCheckQuantity : 0);
                                console.log("businessType == 4: item.baseQuantity:", item.baseQuantity);
                            }
                            //baseQuantity 计算后 赋值
                            item.orgBaseQuantity = item.baseQuantity;
                            /**
                             * 选单计算各种数量
                             */
                            if (businessType == 2 || businessType == 4) {
                                //输入数量的时候

                                //输入数量  并且辅计量数量存在
                                if (item.unitExchangeRate) {
                                    //辅计量数量 = 主计量数量*换算率
                                    let total = Number(item.baseQuantity) / Number(item.unitExchangeRate);
                                    item['subQuantity'] = total.toFixed(4);
                                }
                                //输入数量 并且暂估单价存在
                                if (item.estimatedPrice) {
                                    item['estimatedAmount'] = (item.baseQuantity * item.estimatedPrice).toFixed(2);
                                } else if (item.estimatedAmount) {
                                    item['estimatedPrice'] = (item.estimatedAmount / item.baseQuantity).toFixed(2);
                                }


                                if (item.baseQuantity && item.price && item.taxRate) {
                                    //税率= 单价*数量*税率
                                    let tax = Number(item.baseQuantity) * Number(item.price) * Number(item.taxRate) / 100
                                    item['tax'] = tax.toFixed(4);
                                }

                                if (item.baseQuantity && item.price) {
                                    //数量*单价=金额
                                    let total = Number(item.baseQuantity) * Number(item.price);
                                    item['amount'] = total.toFixed(2);
                                }

                                if (item.baseQuantity && item.includeTaxPrice) {
                                    //数量*含税单价=含税金额
                                    let total = Number(item.baseQuantity) * Number(item.includeTaxPrice);
                                    item['includeTaxAmount'] = total.toFixed(2);
                                }

                            }

                        }

                        this.$emit('editClickOrder', record, 'ischoose')
                    }
                },
            }),
            //选单 默认 参数
            boxPostData: {
                designSearchDtos: [],
                page: {
                    current: 1,
                    size: 10,
                },
                businessType: 2, //1:退货业务 2：非退货业务 3: 退货 + 非退货 4: 发票
                someBusinessType: '0',    // 指定业务类型 默认 0
                startVoucherState: 0,
                endVoucherState: 10
            },
            postData: {},
            selectedRowKeysDetailList: []
        }
    },
    created() {

    },
    computed: {
        invoiceData() {
            return this.$store.state.order.invoiceData;
        }
    },
    watch: {
        selectedRowKeysDetail(val) {
            console.log(val, '111111111111111111111111111')
            let arr = []
            val.forEach(item => {
                arr.push(...this.searchBackDataDetails.filter(item1 => item1.id === item))
            })
            this.selectedRowKeysDetailList = arr
            console.log(arr,11111)
        }
    },
    methods: {
        onCloseDrawer() {

        },
        onSubmit() {
            let record = {}
            record.detailList = this.selectedRowKeysDetailList
            //关闭侧边栏赋值给父组建
            this.drawerVisible = false;
            for (let i = 0; i < record.detailList.length; i++) {

if (this.$route.path == '/production/productionPlan') {
    //生产订单选销售订单 传值
    this.$set(record.detailList[i], 'saleOrderDetailId', record.detailList[i].id);    //id
    this.$set(record.detailList[i], 'needDate', record.detailList[i].deliveryDate);
    this.$set(record.detailList[i], 'planEndDate', record.detailList[i].deliveryDate);
    this.$set(record.detailList[i], 'crmName', record.crmName);
    this.$set(record.detailList[i], 'orderId', '');
    this.$set(record.detailList[i], 'id', '');
}

// record.detailList[i].sourceVoucherId = record.detailList[i].id;
let item = record.detailList[i];
item.sourceVoucherId = record.id;
item.sourceVoucherCode = record.voucherCode;    //来源单号
item.sourceVoucherDate = record.voucherDate;    //来源日期
item.sourceVoucherType = record.sourceVoucherType;    //来源单据



let { businessType } = this.postData;
console.log("选单查询条件：businessType：", businessType);
if (businessType == 1) {
    item.baseQuantity = Math.abs(item.baseQuantity) - (item.cumRetQuantity ? item.cumRetQuantity : 0);
} else if (this.$route.path == '/production/productionPlan') {
    //生产订单不需要处理数量
} else if (businessType == 2) {
    item.baseQuantity = Math.abs(item.baseQuantity) - (item.cumExecuteQuantity ? item.cumExecuteQuantity : 0);
} else if (businessType == 4) {
    item.baseQuantity = Math.abs(item.baseQuantity) - (item.cumInvoiceQuantity ? item.cumInvoiceQuantity : 0);
    console.log("businessType == 4: item.baseQuantity:", item.baseQuantity);
}
// 未质检 数量查询
else if (businessType == 6) {

    item.baseQuantity = Math.abs(item.baseQuantity) - (item.cumQualityCheckQuantity ? item.cumQualityCheckQuantity : 0);
    console.log("businessType == 4: item.baseQuantity:", item.baseQuantity);
}
//baseQuantity 计算后 赋值
item.orgBaseQuantity = item.baseQuantity;
/**
 * 选单计算各种数量
 */
if (businessType == 2 || businessType == 4) {
    //输入数量的时候

    //输入数量  并且辅计量数量存在
    if (item.unitExchangeRate) {
        //辅计量数量 = 主计量数量*换算率
        let total = Number(item.baseQuantity) / Number(item.unitExchangeRate);
        item['subQuantity'] = total.toFixed(4);
    }
    //输入数量 并且暂估单价存在
    if (item.estimatedPrice) {
        item['estimatedAmount'] = (item.baseQuantity * item.estimatedPrice).toFixed(2);
    } else if (item.estimatedAmount) {
        item['estimatedPrice'] = (item.estimatedAmount / item.baseQuantity).toFixed(2);
    }


    if (item.baseQuantity && item.price && item.taxRate) {
        //税率= 单价*数量*税率
        let tax = Number(item.baseQuantity) * Number(item.price) * Number(item.taxRate) / 100
        item['tax'] = tax.toFixed(4);
    }

    if (item.baseQuantity && item.price) {
        //数量*单价=金额
        let total = Number(item.baseQuantity) * Number(item.price);
        item['amount'] = total.toFixed(2);
    }

    if (item.baseQuantity && item.includeTaxPrice) {
        //数量*含税单价=含税金额
        let total = Number(item.baseQuantity) * Number(item.includeTaxPrice);
        item['includeTaxAmount'] = total.toFixed(2);
    }

}

}
this.$emit('editClickOrder', record, 'ischoose')
        },
        onSelectChange(selectedRowKeys) {
            let arr = []
            console.log(selectedRowKeys, 'selectedRowKeysselectedRowKeysselectedRowKeys')
            this.selectedRowKeys = selectedRowKeys
            this.searchBackDataDetails.forEach(i => {
                selectedRowKeys.forEach(j => {
                    if (i.orderId === j) {
                        arr.push(i.id)
                    }
                })
            })
            this.selectedRowKeysDetail = arr
            console.log(arr)
        },
        onSelectChangeDetail(selectedRowKeys) {
            console.log(selectedRowKeys, 'selectedRowKeysselectedRowKeysselectedRowKeys222222222222222222222')
            this.selectedRowKeysDetail = selectedRowKeys

        },
        conversionOrderName,
        deleteMainCommonFild,
        //ischoose存在则是选单
        onOpen(sourceCode, ischoose, title, voucherState, businessType) {
            ischoose ? this.ischoose = true : this.ischoose = false;
            title ? this.drawerTitle = title : this.drawerTitle = '搜索列表';
            voucherState ? this.voucherState = voucherState : this.voucherState = '';
            businessType ? this.choiceBusinessType = businessType : this.choiceBusinessType = null;
            this.sourceCode = sourceCode;

            this.handleDynamicData();

            this.drawerVisible = true;
            this.$nextTick(() => {
                this.$refs.searchInput.focus();
            });
        },
        // 20210728 bbq
        onOpenBox(boxPostData) {
            this.postData = {};
            boxPostData.page = {
                current: this.pagination.current,
                size: this.pagination.pageSize,
            };
            Object.assign(this.boxPostData, boxPostData);
            Object.assign(this.postData, this.boxPostData);
            let { sourceCode, title } = boxPostData;
            this.sourceCode = sourceCode;
            this.drawerTitle = title || '搜索列表';

            this.handleDynamicData();
            this.drawerVisible = true;
            this.$nextTick(() => {
                this.$refs.searchInput.focus();
            });
        },
        onClose() {
            this.drawerVisible = false;
        },
        afterVisibleChange(val) {
            // console.log('visible', val);
        },
        searchList() {
            //搜索
            const { dynamicFormData, searchArray, postData } = this;
            let data = { ...postData };
            console.log("选单010：", this.businessType, this.choiceBusinessType, this.sourceCode);
            //给可以搜索的条件塞入value值
            for (let i = 0; i < searchArray.length; i++) {
                this.$set(searchArray[i], 'value', this.searchText);
            }
            data.designSearchDtos = [];
            for (let i = 0; i < dynamicFormData.length; i++) {
                for (let j = 0; j < searchArray.length; j++) {
                    if (dynamicFormData[i].code != searchArray[j].code) {
                        data.designSearchDtos.push(dynamicFormData[i])
                    } else {
                        data.designSearchDtos.push(searchArray[j])
                    }
                }
            }
            // console.log('--------搜索的值：', data);
            listSearch(data).then((response) => {
                if (response.code === 200) {
                    let backdData = response.data.records;
                    this.pagination.total = response.data.total;

                    // console.log('--------搜索返回值：', backdData);
                    this.searchBackData = backdData;
                    let list = []
                    if (this.$route.path == '/production/productionPlan') {
                        
                        const detaileList = [];
                        this.searchBackData.forEach(record => {
                            record.detailList.forEach(item => {
                                const item1 = { ...item };
                                detaileList.push(item1);
                            })
                            list = this.showDetailes(detaileList)
                        })
                        this.searchBackDataDetails = list
                    } else {
                        //清空详细信息
                        this.searchBackDataDetails = [];

                        this.mouseIndex = null;
                    }

                } else {
                    // this.$message.warning(res.message);
                }
            })
        },
        //改变分页大小
        changePageSize(e) {
            const value = e.target.value;
            let size = Number.parseInt(value);
            if (!size) {
                size = 20;
            }
            if (size > 500) {
                size = 500;
            }
            const { pagination } = this;

            Object.assign(this.pagination, {
                current: 1,
                pageSize: size
            });
            console.log(this.pagination)
            this.searchList();
        },
        remove(record) {
            console.log(record)
        },
        //获取动态字段
        handleDynamicData() {
            let data = {
                source: this.sourceCode
            }
            listDesign(data).then((response) => {
                if (response.code === 200) {
                    const { data } = response;
                    this.dynamicFormData = data;

                    if (this.dynamicFormData) {
                        this.handleSearchCloum();
                        this.handleSearchArray();
                    }

                    if (this.searchCloumsDetails != []) {
                        //列表加载完成在搜索
                        this.searchList();
                    }

                } else {
                    // this.$message.warning(res.message);
                }
            })
        },
        //处理搜索数据
        handleSearchArray() {
            const { dynamicFormData } = this;
            let data = [];
            for (let i = 0; i < dynamicFormData.length; i++) {
                if ((dynamicFormData[i].dataTab == '表头' || dynamicFormData[i].dataTab == '表尾') && dynamicFormData[i].isSearch && dynamicFormData[i].columnType == '文本') {
                    data.push(dynamicFormData[i]);
                }
            }
            if (data.length > 0) {
                this.searchPlaceholder = data.map((o) => o.name).join("/");
                this.searchArray = Object.assign([], data);
            } else {
                this.$message.error('没有可以搜索的条件');
            }
        },
        //动态searchCloums组装
        handleSearchCloum() {
            const { dynamicFormData } = this;
            let searchCloums = [];
            let searchCloumsDetails = [];

            let dynamicFormAllData = dynamicFormData.filter(item => {
                return (item.dataTab == '表头' || item.dataTab == '表尾') && item.onOff == true;
            });

            let dynamicFormAllDataDetails = dynamicFormData.filter(item => {
                return item.dataTab == '明细' && item.onOff == true;
            });

            dynamicFormAllData.forEach(element => {
                let code = element.code;
                if (element.columnType == '搜索选择') {
                    code = IdFieldToNameField(element.code)
                }

                let item = {
                    title: element.name,
                    dataIndex: code,
                    width: 130,
                    ellipsis: true,
                }
                if (element.code == 'businessType') {
                    this.$set(item, 'scopedSlots', { customRender: 'businessType' });
                }
                switch (element.code) {
                    case "sourceVoucherType":
                        item.scopedSlots = { customRender: 'sourceVoucherType' };
                        break;
                    default:
                        break;
                }
                searchCloums.push(item)
            });

            this.searchCloums = searchCloums;
            // Object.assign(this.searchCloums, searchCloums);

            dynamicFormAllDataDetails.forEach(element => {
                let code = element.code;
                if (element.columnType == '搜索选择') {
                    code = IdFieldToNameField(element.code)
                }
                let item = {
                    title: element.name,
                    dataIndex: code,
                    width: 100,
                    ellipsis: true,
                }
                switch (element.code) {
                    case "sourceVoucherType":
                        item.scopedSlots = { customRender: 'sourceVoucherType' };
                        break;
                    default:
                        break;
                }
                searchCloumsDetails.push(item)
            });
            this.searchCloumsDetails = searchCloumsDetails;
        },
        //展示详情
        showDetailes(itemdata) {
            const { unitsDataDetails, unitData } = this;
            let list = itemdata;
            for (let i = 0; i < list.length; i++) {

                for (let j = 0; j < unitsDataDetails.length; j++) {
                    if (list[i].baseUnit == unitsDataDetails[j].id) {
                        list[i].baseUnit = unitsDataDetails[j].name;
                    }

                    if (list[i].subUnit == unitsDataDetails[j].id) {
                        list[i].subUnit = unitsDataDetails[j].name;
                    }
                }

                for (let j = 0; j < unitData.length; j++) {
                    if (list[i].baseUnit == unitData[j].id) {
                        list[i].baseUnit = unitData[j].name;
                    }
                }
            }
            if (this.$route.path == '/production/productionPlan') {
                console.log(list)
                return list
            } else {
                this.searchBackDataDetails = list;
            }
        },
        //去除数据中的id
        copyRemoveIdData(data) {
            let backData = JSON.parse(JSON.stringify(data));
            let details = backData.detailList;
            backData.id = '';
            backData.voucherState = 0;

            for (const key in details) {
                details[key].id = '';
                details[key].orderId = '';
            }
            return backData;
        },
        rowClassName(record, index) {
            return this.mouseIndex == index ? 'hoverRowStyl' : '';
        },
        handleBusinessType(record) {
            let back = '';
            this.dynamicFormData.forEach(item => {
                //处理业务类型的展示
                let val = [];
                if (item.code == 'businessType') {
                    val = JSON.parse(item.val);

                    let a = val.filter(c => { return c.key == record.businessType });
                    if (a.length > 0) {
                        back = a[0].label;
                    }
                }
            });
            return back;
        },
        onSelectChangeMain(keys, rows) {
            //表头选择数据
            this.selectedRowMainKeys = keys;
            this.selectedRowMainData = rows;
            console.log(keys, rows);
        },
        onSelectChangeDetails(keys, rows) {
            //明细选择数据
            this.selectedRowDetailsKeys = keys;
            this.selectedRowDetailsData = rows;
            console.log(keys, rows);
        }

    },
}
</script>
<style lang="less">
.drawer-box .search-btn {
    margin-top: 10px;
}

.drawer-box .ant-drawer-body {
    padding-bottom: 80px;
}

.drawer-box .ant-table-body {
    cursor: pointer;
}

.drawer-box .ant-drawer-content {
    z-index: 25;
}

.drawer-box .details-title {
    font-weight: bold;
}

.search-table-list .ant-table-body {
    min-height: 120px !important;
}

.drawer-box .hoverRowStyl {
    background-color: rgb(230, 247, 255);
}
</style>